#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickImageProvider>
#include "qrencode.h"

class QRImageProvider : public QQuickImageProvider
{
public:
    QRImageProvider()
        : QQuickImageProvider(QQuickImageProvider::Pixmap)
    {}

    QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override
    {
        int width = 150;
        int height = 150;
        if (size) {
            *size = QSize(width, height);
        }
        QRcode *qrcode = QRcode_encodeString8bit(id.toStdString().c_str(), 0, QR_ECLEVEL_L);

        int qsize = qrcode->width;

        QImage img(qsize, qsize, QImage::Format_Mono);
        img.fill(1);

        for (int y = 0; y < qsize; ++y) {
            for (int x = 0; x < qsize; ++x) {
                bool value = qrcode->data[y * qsize + x] & 1;
                img.setPixel(x, y, value ? 0 : 1);
            }
        }
        QRcode_free(qrcode);
        QPixmap pix = QPixmap::fromImage(img);

        return pix;
    }
};

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/Scan_The/Main.qml"));
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreationFailed,
        &app,
        []() { QCoreApplication::exit(-1); },
        Qt::QueuedConnection);

    engine.addImageProvider(QLatin1String("login"), new QRImageProvider);
    engine.load(url);

    return app.exec();
}
